package com.ebook.server.service;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.springframework.stereotype.Service;

@Service
public class FileOperateService {

	/**
	 * 下载文件
	 * @param request
	 * @param response
	 * @param storeName
	 * @param contentType
	 * @param realName
	 * @throws Exception
	 */
//	public static void download(HttpServletRequest request,  
//			HttpServletResponse response, String storeName, String contentType,  
//            String realName) throws Exception {  
//        	response.setContentType("text/html;charset=UTF-8");  
//        	request.setCharacterEncoding("UTF-8");  
//        	BufferedInputStream bis = null;  
//        	BufferedOutputStream bos = null;  
//  
//        	String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;  
//        	String downLoadPath = ctxPath + storeName;  
//  
//        	long fileLength = new File(downLoadPath).length();  
//  
//	        response.setContentType(contentType);  
//	        response.setHeader("Content-disposition", "attachment; filename="  
//	                + new String(realName.getBytes("utf-8"), "ISO8859-1"));  
//	        response.setHeader("Content-Length", String.valueOf(fileLength));  
//	  
//	        bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
//	        bos = new BufferedOutputStream(response.getOutputStream());  
//	        byte[] buff = new byte[2048];  
//	        int bytesRead;  
//	        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
//	            bos.write(buff, 0, bytesRead);  
//	        }  
//	        bis.close();  
//	        bos.close();  
//		}
	
	public String getFileJsonString(String fileName) {
		String ret = null;
		try {
			// 读取文件
			FileInputStream fileInputStream = new FileInputStream(fileName);   
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();   
			int i;   
			while ((i = fileInputStream.read()) != -1) {   
			    byteArrayOutputStream.write(i);   
			}
			fileInputStream.close();
			
			// 把文件存在一个字节数组中
			byte[] fileStringArray = byteArrayOutputStream.toByteArray();
			byteArrayOutputStream.close();
			ret = new String(fileStringArray, "ISO-8859-1");
//			System.out.println(ret);
			
			
			////////////
//			FileOutputStream fileOutputStream = new FileOutputStream("d:/2.txt");
//			fileOutputStream.write(ret.getBytes("ISO-8859-1"));
//			fileOutputStream.flush();
//			fileOutputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {			
			e.printStackTrace();
		}

		return ret;
	}

}
